package net.lcheng.commons.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by qiliping on 15/12/22.
 * 短信工具类
 */
public class MessageUtils {
    private final static String serverUrl = "http://222.73.117.158/msg/HttpBatchSendSM";
    private final static String account = "zhongtou-01";
    private final static String password = "Txb123456";
    private final static String needstatus = "true";
    /**
     * 发送短信
     * @param phone 接收手机
     * @param msg 短信内容
     * */
    public static int sendMsg(String phone,String msg) throws IOException {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("account", account));
        formparams.add(new BasicNameValuePair("pswd", password));
        formparams.add(new BasicNameValuePair("mobile", phone));
        formparams.add(new BasicNameValuePair("msg", msg));
        formparams.add(new BasicNameValuePair("needstatus", needstatus));

        HttpEntity reqEntity = new UrlEncodedFormEntity(formparams, "utf-8");
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpPost post = new HttpPost(serverUrl);
        post.setEntity(reqEntity);
        post.setConfig(requestConfig);
        HttpResponse response = httpclient.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity resEntity = response.getEntity();
            String message = EntityUtils.toString(resEntity, "utf-8");
            String[] res = message.split("\n");
            String[] resStatus = res[0].split(",");
            if(resStatus[1].equals("0")){
                //发送成功
                return 0;
            }else{
                return Integer.valueOf(resStatus[1]);
            }

        } else {
            return 500;
        }
    }

}
